package com.gzc.just.play.last.war.balanceserver.handler;



import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;

import com.gzc.just.play.last.war.balanceserver.manager.ServerManager;

import io.netty.channel.ChannelHandlerContext;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;



import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;



/**

 * 鏈嶅姟鍣ㄥ垪琛ㄥ勭悊鍣

 * 澶勭悊鑾峰彇鏈嶅姟鍣ㄥ垪琛ㄧ殑娑堟伅

 */

@Component("balance-serverListHandler")
public class ServerListHandler implements SimpleMessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(ServerListHandler.class);

    

    @Autowired

    private ServerManager serverManager;

    

    private static final int SERVER_LIST = 2003;

    

    @Override

    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {

        // 浠庢秷鎭涓瑙ｆ瀽鏈嶅姟鍣ㄧ被鍨嬶紙鍙閫夛級

        String serverType = extractServerType(message);

        

        // 鑾峰彇鏈嶅姟鍣ㄥ垪琛

        List<Map<String, Object>> serverList;

        if (serverType != null && !serverType.trim().isEmpty()) {

            // 鑾峰彇鎸囧畾绫诲瀷鐨勬湇鍔″櫒鍒楄〃

            serverList = serverManager.getServersByType(serverType);

            logger.info("Client requested server list of type: {}", serverType);

        } else {

            // 鑾峰彇鎵鏈夋湇鍔″櫒鐨勫垪琛

            List<ServerManager.ServerInfo> serverInfoList = serverManager.getAllServers();

            // 杞鎹涓篗ap鍒楄〃

            serverList = new ArrayList<>();

            for (ServerManager.ServerInfo serverInfo : serverInfoList) {

                Map<String, Object> serverMap = new HashMap<>();

                serverMap.put("serverId", serverInfo.getServerId());

                serverMap.put("serverName", serverInfo.getServerName());

                serverMap.put("serverType", serverInfo.getServerType());

                serverMap.put("host", serverInfo.getHost());

                serverMap.put("port", serverInfo.getPort());

                serverMap.put("load", serverInfo.getCurrentLoad());

                serverMap.put("maxLoad", serverInfo.getMaxLoad());

                serverMap.put("status", serverInfo.getStatus());

                serverMap.put("registerTime", serverInfo.getRegisterTime());

                serverMap.put("lastHeartbeatTime", serverInfo.getLastHeartbeatTime());

                serverMap.put("loadPercentage", serverInfo.getLoadPercentage());

                serverList.add(serverMap);

            }

            logger.info("Client requested all server list");

        }

        

        // 鍙戦佹湇鍔″櫒鍒楄〃鍝嶅簲

        sendServerListResponse(ctx, serverList, true, "Server list retrieved successfully");

        

        logger.info("Returning {} servers in the list", serverList.size());

    }

    

    private String extractServerType(Object message) {

        // 瀹為檯瀹炵幇涓搴旇ヤ粠娑堟伅瀵硅薄涓瑙ｆ瀽鏈嶅姟鍣ㄧ被鍨

        // 杩欓噷杩斿洖null琛ㄧず鑾峰彇鎵鏈夋湇鍔″櫒

        return null;

    }

    

    private void sendServerListResponse(ChannelHandlerContext ctx, List<Map<String, Object>> serverList, 

                                      boolean success, String message) {

        // 瀹為檯瀹炵幇涓搴旇ユ瀯閫犲苟鍙戦佹湇鍔″櫒鍒楄〃鍝嶅簲娑堟伅

        logger.info("Sending server list response: success={}, message={}, serverCount={}", 

                   success, message, serverList.size());

        

        // 绀轰緥锛氭墦鍗版湇鍔″櫒鍒楄〃鍐呭癸紙瀹為檯瀹炵幇涓搴旇ュ皢鍒楄〃搴忓垪鍖栦负鍝嶅簲娑堟伅锛

        if (success && !serverList.isEmpty()) {

            logger.debug("Server list content:");

            for (Map<String, Object> server : serverList) {

                logger.debug("Server ID: {}, Name: {}, Type: {}, Status: {}, Load: {}/{}", 

                           server.get("serverId"), 

                           server.get("serverName"), 

                           server.get("serverType"), 

                           server.get("status"), 

                           server.get("load"), 

                           server.get("maxLoad"));

            }

        }

    }



    @Override

    public int getMessageId() {

        return SERVER_LIST;

    }

    

    @Override

    public String getName() {

        return "ServerListHandler";

    }

    

    @Override

    public Logger getLogger() {

        return logger;

    }

}